package zcw.com.lib_leet_code;

import java.util.LinkedHashMap;

/**
 * Created by 朱城委 on 2021/7/14.<br><br>
 *
 * 字符串中的第一个唯一字符
 */
public class Topic387 {
    public static void main(String[] args) {
        Topic387 instance = new Topic387();

        System.out.println(instance.firstUniqChar("leetcode"));
        System.out.println(instance.firstUniqChar("loveleetcode"));
        System.out.println(instance.firstUniqChar("aabb"));
    }

    public int firstUniqChar(String s) {
        int[] counter = new int[26];
        for(char ch : s.toCharArray()) {
            counter[ch - 'a']++;
        }

        for(int i = 0; i < s.length(); i++) {
            if(counter[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }

        return -1;
    }

    public int firstUniqChar3(String s) {
        int index = -1;

        for(int i = 0; i < 26; i++) {
            char ch = (char) ('a' + i);

            int tempIndex = s.indexOf(ch);
            if(tempIndex != -1 && s.lastIndexOf(ch) == tempIndex) {
                if(index == -1 || tempIndex < index) {
                    index = tempIndex;
                }
            }
        }

        return index;
    }

    public int firstUniqChar2(String s) {
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
        for(char ch : s.toCharArray()) {
            if(map.containsKey(ch)) {
                map.put(ch, map.get(ch) + 1);
            }
            else {
                map.put(ch, 1);
            }
        }

        for(char ch : map.keySet()) {
            if(map.get(ch) == 1) {
                return s.indexOf(ch);
            }
        }

        return -1;
    }
}
